import { NodeEventType, Component, Node } from 'cc';
import { EventManager } from '../EventManager';

/** UI组件的基类，提供一些便于开发的函数 */
export class UIBase extends Component {

    /** 所有节点映射 */
    view: { [name: string]: Node }

    /** 绑定所有节点到view对象 */
    bindView() {
        this.view = {}
        this.setView(this.node)
    }

    private setView(parent: Node) {
        let items = parent.children;
        for (let i = 0; i < items.length; i++) {
            this.view[items[i].name] = items[i]
            this.setView(items[i])
        }
    }

    /** 节点绑定点击事件 */
    bindClick(node: Node, func: Function, ctx?: any) {
        node.off(NodeEventType.TOUCH_END)
        node.on(NodeEventType.TOUCH_END, () => {
            if (ctx) {
                func.call(ctx)
            } else {
                func()
            }
        })
    }

    protected onDestroy() {
        EventManager.Ins.offByCtx(this)
    }
}